//
//  UdpClient.m
//  socketDemo
//
//  Created by 吳瀾洲 on 2020/8/3.
//  Copyright © 2020 kingboyrang. All rights reserved.
//

#import "UdpManager.h"
#import "GCDAsyncUdpSocket.h"

NSString *const kUDPSendSuccessNotification  = @"kUDPSendSuccessNotification";
NSString *const kUDPSendFailedNotification  = @"kUDPSendFailedNotification";

#define kUdpClientSendTag 1

@interface UdpManager () <GCDAsyncUdpSocketDelegate>{
    
}

@property (nonatomic,strong) GCDAsyncUdpSocket *udpSocket;

@end

@implementation UdpManager


+ (UdpManager *)shareInstance{
    static dispatch_once_t pred = 0;
       __strong static UdpManager *_sharedObject = nil;
       dispatch_once(&pred, ^{
           _sharedObject = [[self alloc] init]; // or some other init method
       });
       return _sharedObject;
}

//发送数据
- (void)sendData:(NSData *)data port:(uint16_t)port toHost:(NSString *)host{
    [self.udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:kUdpClientSendTag];
}
- (void)sendData:(NSData *)data port:(uint16_t)port toHost:(NSString *)host tag:(NSInteger)tag{
    [self.udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:tag];
}



#pragma mark 属性
- (GCDAsyncUdpSocket *)udpSocket{
    if (_udpSocket ==nil) {
        _udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        
        //监听
        NSError * error = nil;
        [_udpSocket enableBroadcast:YES error:&error];
        if (error) {//监听错误打印错误信息
            NSLog(@"error:%@",error);
        }else {//监听成功则开始接收信息
            //[_udpSocket beginReceiving:&error];
        }
    }
    return _udpSocket;
}



#pragma mark GCDAsyncUdpSocketDelegate Methods
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address{
    
    NSLog(@"upd 连接到主机");
    if (self.connectStateChangedBlock) {
        self.connectStateChangedBlock(UDPConnectSuccess);
    }
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError * _Nullable)error{
    
    NSLog(@"upd 连接到主机失败,error = %@",error);
    if (self.connectStateChangedBlock) {
        self.connectStateChangedBlock(UDPConnectFailed);
    }
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    NSLog(@"发送信息成功");
    [[NSNotificationCenter defaultCenter] postNotificationName:kUDPSendSuccessNotification object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",tag],@"tag", nil]];
    
    if (self.sendDataBlock) {
        self.sendDataBlock(YES, tag, nil);
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSendDataWithTag:status:error:)]) {
        [self.delegate didSendDataWithTag:tag status:YES error:nil];
    }
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
    NSLog(@"发送信息失败");
    [[NSNotificationCenter defaultCenter] postNotificationName:kUDPSendFailedNotification object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",tag],@"tag",error,"error", nil]];
    
    if (self.sendDataBlock) {
        self.sendDataBlock(NO, tag, error);
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSendDataWithTag:status:error:)]) {
        [self.delegate didSendDataWithTag:tag status:NO error:error];
    }
}
- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError  * _Nullable)error{
    NSLog(@"udp 连接断开");
    if (self.connectStateChangedBlock) {
        self.connectStateChangedBlock(UDPConnectClose);
    }
}
@end
